import { ISession, ITarget, IWork } from '../../..';
import { kernel, model, schema } from '@/ts/base';
import { PeriodType } from '@/ts/base/enum';
import { IDistributionTask } from '../../../thing/standard/distributiontask';
import { PageAll } from '@/ts/core/public';

type Base = model.TaskContentBase<model.TaskContentType>;

export interface IDistribution<C extends Base = Base> {
  /** 键 */
  key: string;
  /** 空间 */
  target: ITarget;
  /** 元数据 */
  metadata: schema.XDistribution;
  /** 主键 */
  id: string;
  /** 分发类型 */
  periodType: PeriodType;
  /** 时期 */
  period: string;
  /** 办事 */
  workId: string | undefined;
  /** 任务 */
  task: IDistributionTask;
  /** 内容 */
  data: C;
  /** 返回已发起的任务数量 */
  existsReceptionCount(): Promise<number>;
}

export abstract class Distribution<C extends Base> implements IDistribution<C> {
  constructor(task: IDistributionTask, metadata: schema.XDistribution) {
    this.task = task;
    this.metadata = metadata;
  }
  abstract data: C;
  metadata: schema.XDistribution;
  task: IDistributionTask;

  get id() {
    return this.metadata.id;
  }
  get key() {
    return this.metadata.id;
  }
  get target() {
    return this.task.directory.target;
  }
  get typeName() {
    return this.metadata.typeName;
  }
  get periodType() {
    return this.metadata.periodType;
  }
  get period() {
    return this.metadata.period;
  }
  get workId() {
    return this.metadata.content.workId;
  }
  get treeId() {
    return this.metadata.content.treeId;
  }
  get nodeColl() {
    return this.task.directory.resource.reportTreeNodeColl;
  }

  protected async findWork(session: ISession): Promise<IWork> {
    const res = await kernel.queryWorkDefine({
      id: this.workId,
      belongId: '0',
      page: PageAll,
    });
    if (res.success && res.data && res.data.result && res.data.result.length > 0) {
      var define = res.data.result[0];

      var target = session.target.space.targets.find((i) => i.id === define.shareId);
      if (target) {
        for (var app of await target.directory.loadAllApplication()) {
          const work = await app.findWork(this.workId, define.applicationId);
          if (work) {
            console.log(work)
            return work as IWork;
          }
        }
      } else {
        throw new Error('找不到接收任务群聊的会话，无法加载办事');
      }
    }
    throw new Error('未获取到相关办事信息!');
  }

  async existsReceptionCount(): Promise<number> {
    const count = await this.target.resource.receptionColl.count({
      options: {
        match: {
          taskId: this.task.id,
          period: this.period,
          distId: this.id,
          _and_: [
            { instanceId: { _exists_: true } },
            { instanceId: { _ne_: '' } },
            { instanceId: { _ne_: null } },
          ],
        },
      },
    });
    return count;
  }
}
